package login.ops;

import login.Util;
import org.slf4j.LoggerFactory;
import tr.gov.tubitak.uekae.esya.api.signature.ContainerValidationResult;
import tr.gov.tubitak.uekae.esya.api.signature.ContainerValidationResultType;
import tr.gov.tubitak.uekae.esya.api.signature.SignatureContainer;
import tr.gov.tubitak.uekae.esya.api.signature.SignatureFactory;

import java.io.ByteArrayInputStream;

/**
 * Provides operations for new signing interface
 *
 * @author suleyman.uslu
 */
public class SignatureContainerOps implements SignatureOps {

    private static org.slf4j.Logger msLogger = LoggerFactory.getLogger(SignatureContainerOps.class);

    private SignatureContainer container;

    /**
     * Generate signature container from given byte array
     * @param containerBytes    bytes of which container consists
     */
    public SignatureContainerOps(byte[] containerBytes) {

        if(container == null) {

            try {
                ByteArrayInputStream bais = new ByteArrayInputStream(containerBytes);
                container = SignatureFactory.readContainer(bais, Util.createNewContext());
            }
            catch (Exception e) {
                msLogger.debug("error in creating container from bytes", e);
            }
        }
    }

    /**
     * Verifies given signature container
     * @return container validation result
     */
    public boolean verify() {

        ContainerValidationResult cvr = container.verifyAll();
        msLogger.debug(cvr.toString());
        return cvr.getResultType().equals(ContainerValidationResultType.ALL_VALID);
    }

    /**
     * Finds the name of certificate owner
     * @return name of certificate owner
     */
    public String getSignerName() {

        return container.getSignatures().get(0).getSignerCertificate().getSubject().getCommonNameAttribute();
    }
}
